<template>
  <inline-Modal
    :visible="visible"
    title="不涉及项配置"
    @ok="handelOk()"
    @cancel="handelCancel()"
  >
    <div class="not-involve-container">
      <a-form-model ref="ruleForm" :model="form">
        <div class="config-content">
          <div class="search">
            <a-select
              v-model="form.modelId"
              placeholder="请选择评价标准"
              @change="changeResponsible($event)"
              :laoding="evaLoading"
            >
              <a-select-option
                :value="item.uuid"
                v-for="item in evaSource"
                :key="item.uuid"
              >
                {{ item.modelName }}
              </a-select-option>
            </a-select>
            <a-select
              v-model="form.responsibleSubject"
              placeholder="请选择责任单位"
              allowClear
              @change="changeResponsible($event)"
            >
              <a-select-option
                :value="item.dicItemCode"
                v-for="item in unitSource"
                :key="item.id"
              >
                {{ item.dicItemName }}
              </a-select-option>
            </a-select>
            <a-button type="primary" @click="getTreeData()"> 查询 </a-button>
          </div>
          <div class="body">
            <div class="tree-container">
              <div class="button-group">
                <div
                  class="button"
                  :class="{ checked: dealSatus == '' }"
                  @click="switchButton('')"
                >
                  全部({{
                    count.allCount > 999 ? "999+" : count.allCount || 0
                  }})
                </div>
                <div
                  class="button"
                  :class="{ checked: dealSatus == '3' }"
                  @click="switchButton('3')"
                >
                  已选({{
                    count.chooseCount > 999 ? "999+" : count.chooseCount || 0
                  }})
                </div>
                <div
                  class="button"
                  :class="{ checked: dealSatus == '4' }"
                  @click="switchButton('4')"
                >
                  未选({{
                    count.noChooseCount > 999
                      ? "999+"
                      : count.noChooseCount || 0
                  }})
                </div>
              </div>
              <a-empty v-if="treeData.length == 0" />
              <a-tree
                v-else
                show-icon
                :default-expand-all="true"
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :tree-data="treeData"
                @expand="onExpand"
                @select="onSelect"
                :replaceFields="{
                  children: 'childs',
                  title: 'evaluationName',
                  key: 'uuid',
                }"
              >
                <template slot="title" slot-scope="{ evaluationName }">
                  <div class="custom-tree-item flex" :title="evaluationName">
                    <div class="label">{{ evaluationName }}</div>
                  </div>
                </template>
                <!-- 文件夹图标 -->
                <template slot="custom" slot-scope="{ expanded, childs }">
                  <a-icon
                    :type="
                      childs && childs.length > 0
                        ? expanded
                          ? 'folder-open'
                          : 'folder'
                        : 'file'
                    "
                    :class="
                      childs && childs.length > 0 ? 'folder-icon' : 'file-icon'
                    "
                  />
                </template>
              </a-tree>
            </div>
            <div class="right-container">
              <div class="list">
                <vxe-table
                  ref="xTable"
                  height="99%"
                  align="center"
                  show-overflow
                  show-header-overflow
                  border="inner"
                  :data="tableData"
                  :column-config="{ resizable: true }"
                  size="small"
                  :loading="loading"
                >
                  <!-- 新增权限才展示多选框 -->
                  <vxe-column width="60">
                    <template #header>
                      <a-checkbox
                        v-model="allcChecked"
                        :indeterminate="indeterminate"
                        @change="allClick($event)"
                        :disabled="checkDisabled"
                      >
                      </a-checkbox>
                    </template>
                    <template #default="{ row }">
                      <a-checkbox
                        :disabled="checkDisabled"
                        v-model="row.check"
                        @change="changeItem($event, row)"
                      >
                      </a-checkbox>
                    </template>
                  </vxe-column>
                  <vxe-column type="seq" width="80" title="序号"></vxe-column>
                  <vxe-column field="assessmentContent" title="五级指标">
                  </vxe-column>
                  <vxe-column field="methods" title="审查资料及方式">
                  </vxe-column>
                  <vxe-column field="singleScore" title="总分"> </vxe-column>
                  <vxe-column field="responsibleSubjectDesc" title="责任主体">
                  </vxe-column>
                </vxe-table>
              </div>
              <!-- <div class="pager-container">
                <vxe-pager
                  size="small"
                  background
                  :current-page.sync="pager.page"
                  :page-size.sync="pager.pageSize"
                  :total="pager.total"
                  :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
                  :page-sizes="[20, 50, 100, 500]"
                  @page-change="paginationChange"
                >
                  <template #left>
                    <div class="vxe-pager-left-tip-container">
                      共<span>{{ pager.total }}</span
                      >条
                    </div>
                  </template>
                </vxe-pager>
              </div> -->
            </div>
          </div>
        </div>
      </a-form-model>
    </div>
  </inline-Modal>
</template>

<script>
import { addAttributeByKey } from "@/utils/index.js";
import { flatTreeData } from "@/utils/util";
import { axios } from "@/utils/request";
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    soucre: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      buttonLoading: false,
      form: {
        //评价标准
        modelId: undefined,
        //责任单位
        responsibleSubject: undefined,
      },
      //分页
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 999,
        total: 0,
      },
      checkRowKeys: [],
      allcChecked: false,
      indeterminate: false,
      checkDisabled: false,
      checkList: [],
      //树
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      treeId: "",
      //责任单位
      unitSource: [],
      unitLoading: false,
      //评价标准名称
      evaSource: [],
      evaLoading: false,
      //状态
      dealSatus: "",
      //数量
      count: {},
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getDetail();
          this.getData();
        }
      },
      immediate: true,
    },
  },
  mounted() {},
  methods: {
    //选择状态
    switchButton(type) {
      this.dealSatus = type;
      this.getTreeData();
    },

    //选择设计单位
    changeResponsible() {
      this.getTreeData();
      this.getBsjxTotal();
    },

    getData() {
      Promise.all([this.getSecTypeList(), this.getEvaList()]);
    },

    //查询责任单位
    getSecTypeList() {
      this.unitLoading = true;
      return new Promise((resolve, reject) => {
        this.$post("/system/dicSet/getDicItemByCode", {
          code: "secType",
        })
          .then((res) => {
            let { data } = res;
            this.unitSource = data || [];
            resolve();
          })
          .catch((_) => {
            this.unitSource = [];
            reject();
          })
          .finally((_) => {
            this.unitLoading = false;
          });
      });
    },
    //查询评价标准-下拉框
    getEvaList() {
      this.evaLoading = true;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/qeModel/list`,
            { modelName: "", province: "", modelType: "1" },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.evaSource = res?.data ?? [];
            this.form.modelId = this.evaSource?.[0]?.uuid || undefined;
            if (!this.form.modelId) {
              return;
            }
            this.getTreeData();
            this.getBsjxTotal();
            resolve();
          })
          .catch((_) => {
            this.form.modelId = undefined;
            this.evaSource = [];
            reject();
          })
          .finally((_) => {
            this.evaLoading = false;
          });
      });
    },
    //查询不涉及数量
    getBsjxTotal() {
      return new Promise((resolve, reject) => {
        let { tenantCode = "" } = this.$parent.condition;
        let { form } = this;
        let responsibleSubject = form.responsibleSubject
          ? form.responsibleSubject
          : "";
        axios
          .get(
            `/probusiness/qeNew/getBSJXTotalData?modelId=${form.modelId}&responsibleSubject=${responsibleSubject}&tenantCode=${tenantCode}`,
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.count = res.data;
            resolve();
          })
          .catch((_) => {
            this.count = {};
            reject();
          });
      });
    },

    //查询树结构
    getTreeData() {
      this.loading = true;
      let { form } = this;
      return new Promise((resolve, reject) => {
        let { tenantCode = "" } = this.$parent.condition;
        axios
          .post(
            `/probusiness/qeNew/getPJZBList?modelId=${form.modelId}`,
            {
              responsibleSubject: form.responsibleSubject,
              status: this.dealSatus,
              tenantCode,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let source = res?.data || [];
            this.treeData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childs"
            );

            if (this.treeData.length > 0) {
              this.getFirstTreeNode();
            }

            resolve();
          })
          .catch((_) => {
            this.loading = false;
            this.treeData = [];
            reject();
          });
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      let flatData = flatTreeData(treeData, "childs");
      let item = flatData.find((v) => !v.childs || v.childs.length == 0);
      this.expandedKeys = [item.uuid];
      this.selectedKeys = [item.uuid];
      this.treeId = item.uuid;
      this.pager.page = 1;
      this.getTableData();
    },

    //查询详情
    getDetail() {
      let { tenantCode = "" } = this.$parent.condition;
      axios
        .get(
          `/probusiness/qeNew/editViewNotContainConfig?tenantCode=${tenantCode}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        .then((res) => {
          this.checkRowKeys = res.data || [];
        })
        .catch((_) => {
          this.checkRowKeys = [];
        });
    },

    //查询列表
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let { responsibleSubject = "" } = this.form;
      let { tenantCode = "" } = this.$parent.condition;
      return new Promise((resolve, reject) => {
        axios
          .post(
            `/probusiness/qeNew/getPJZBContentList?pageNo=${page}&pageSize=${pageSize}&id=${this.treeId}`,
            {
              id: this.treeId,
              responsibleSubject,
              status: this.dealSatus,
              tenantCode,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.tableData = res.data?.rows || [];
            this.pager.total = res?.data.totalCount || 0;
            //一键配置
            if (this.checkDisabled) {
              this.indeterminate = false;
              this.allcChecked = true;
              this.tableData.forEach((item) => {
                this.$set(item, "check", true);
              });
            } else {
              //选择配置
              this.tableData.forEach((item) => {
                this.$set(item, "check", false);
                this.checkRowKeys.forEach((v) => {
                  if (item.uuid == v) {
                    item.check = true;
                  }
                });
              });
              let ids = [];
              try {
                this.tableData.forEach((v) => {
                  if (v.check) {
                    throw v;
                  }
                });
                this.indeterminate = false;
              } catch (error) {
                this.indeterminate = true;
              }
              this.tableData.forEach((v) => {
                if (v.check) {
                  ids.push(v);
                }
              });
              if (ids.length == this.tableData.length) {
                this.indeterminate = false;
                this.allcChecked = true;
              } else {
                this.allcChecked = false;
              }
            }

            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    //全选
    allClick(e) {
      this.indeterminate = false;
      let ev = this.allcChecked;
      if (ev) {
        this.tableData.forEach((v) => {
          this.$set(v, "check", true);
        });
      } else {
        this.tableData.forEach((v) => {
          this.$set(v, "check", false);
        });
      }
      let ids = [];
      this.tableData.forEach((v) => {
        if (v.check) {
          ids.push(v.uuid);
          if (this.checkList.indexOf(v.uuid) == -1) {
            this.checkList.push(v.uuid);
          }
        } else {
          var _index = this.checkList.indexOf(v.uuid);
          if (_index != -1) {
            this.checkList.splice(_index, 1);
          }
        }
      });
      this.checkRowKeys = this.checkList;
    },

    //单选
    changeItem(event, row) {
      let { checked } = event.target;
      let { mergeItem } = row;
      let ids = [];
      let merge = [];
      if (mergeItem) {
        merge = mergeItem.split(",");
        this.tableData.forEach((v) => {
          if (merge.includes(v.serialNumber + "")) {
            if (checked) {
              v.check = true;
            } else {
              v.check = false;
            }
          }
        });
      }
      try {
        this.tableData.forEach((v) => {
          if (v.check) {
            throw v;
          }
        });
        this.indeterminate = false;
      } catch (error) {
        this.indeterminate = true;
      }
      this.tableData.forEach((key) => {
        if (key.check) {
          ids.push(key.uuid);
          if (this.checkList.indexOf(key.uuid) == -1) {
            this.checkList.push(key.uuid);
          }
        }
      });
      if (ids.length == this.tableData.length) {
        this.indeterminate = false;
        this.allcChecked = true;
      } else {
        this.allcChecked = false;
      }
      if (!checked) {
        if (mergeItem) {
          let list = this.tableData.filter((v) =>
            merge.includes(v.serialNumber + "")
          );
          list.forEach((item) => {
            var _index = this.checkList.indexOf(item.uuid);
            if (_index != -1) {
              this.checkList.splice(_index, 1);
            }
          });
        } else {
          var _index = this.checkList.indexOf(row.uuid);
          if (_index != -1) {
            this.checkList.splice(_index, 1);
          }
        }
      }
      this.checkRowKeys = this.checkList;
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    onSelect(selectedKeys, event) {
      let { uuid } = event.node.dataRef;
      this.selectedKeys = selectedKeys;
      this.selectedKeys = [uuid];
      this.treeId = uuid;
      this.allcChecked = false;
      this.indeterminate = false;
      this.pager.page = 1;
      this.getTableData();
    },

    //提交
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          let { checkRowKeys } = this;
          let { tenantCode = "" } = this.$parent.condition;
          let formJson = {
            evaluationContentIdLs: checkRowKeys,
            tenantCode,
          };
          axios
            .post(`/probusiness/qeNew/saveOrUpdateNotContainConfig`, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success(
                  res.message ? res.message : "操作成功",
                  1.5
                );
                this.$emit("ok");
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {})
            .finally((_) => {
              this.buttonLoading = false;
            });
        }
      });
    },
    handelCancel() {
      this.$emit("cancel");
    },
  },
};
</script>

<style lang="less" scoped>
@primary-color: @primary-color;
.not-involve-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  /deep/.ant-form {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .config-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .search {
        margin: 0 0 10px 0;
        display: flex;
        .ant-select {
          width: 200px;
          margin-right: 16px;
        }
      }
      .body {
        flex: 1;
        display: flex;
        overflow: hidden;
        .tree-container {
          flex-shrink: 0;
          width: 342px;
          box-sizing: border-box;
          padding: 0 10px 0px 10px;
          border-right: 1px solid @border-color;
          overflow: auto;
          position: relative;
          .button-group {
            display: flex;
            padding: 0px 10px 10px 10px;
            .button {
              cursor: pointer;
              flex: 1;
              height: 36px;
              background: #ffffff;
              border: 1px solid @primary-color;
              border-radius: 4px;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-right: 10px;
              font-size: 14px;
              font-family: Microsoft YaHei;
              font-weight: 400;
              color: @primary-color;
              &:last-of-type {
                margin-right: 0;
              }
              &.checked {
                background: @primary-color;
                color: #ffffff;
              }
            }
          }
          .ant-tree {
            .ant-tree-node-content-wrapper {
              width: calc(100% - 34px);
              &.ant-tree-node-selected {
                background: #f5f7fc !important;
                color: @primary-color;
              }
              .folder-icon {
                color: #f5a623;
              }
              .file-icon {
                color: #54baff;
              }
              .ant-tree-title {
                width: calc(100% - 24px);
                display: inline-block;
                .custom-tree-item {
                  width: 100%;
                  height: 100%;
                  .label {
                    flex: 1;
                    overflow: hidden;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    margin-right: 10px;
                  }
                  .value {
                    color: #525a5d;
                    span {
                      color: @primary-color;
                    }
                  }
                }
              }
            }
          }
          .ant-empty {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
          }
        }
        .right-container {
          flex-shrink: 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          box-sizing: border-box;
          padding-left: 14px;
          .list {
            height: 100%;
            flex: 1;
          }
          .pager-container {
            flex-shrink: 0;
          }
        }
      }
    }
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        width: 130px;
        flex-shrink: 0;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        textarea {
          height: 80px;
        }
        .ant-calendar-picker {
          width: 100%;
        }
      }
    }
  }
}
</style>
